package org.ph.share.lock.test.thread2;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 票售卖实践
 * 理解临界区问题
 *
 * @author Hush.
 * @since 2023/5/17 18:43
 */
@Slf4j
public class TicketSale {
    public static void main(String[] args) throws InterruptedException {
        SaleWindow window = new SaleWindow(1000);
        List<Thread> threads = new ArrayList<>();
        List<Integer> tickets = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 1000; i++) {
            Thread thread = new Thread(() -> {
                int sale;
                try {
                    Thread.sleep(10);
                    sale = window.sale(getRandomNum());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                tickets.add(sale);
            });
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }
        int sum = tickets.stream().mapToInt(i -> i).sum();
        log.info("sum:{},count:{}", sum, window.getCount());
    }

    static Random random = new Random();

    public static int getRandomNum() {
        return random.nextInt(10);
    }

}

/**
 * 售票窗口
 *
 * @author Hush.
 * @since 2023/5/17 18:45
 */
class SaleWindow {
    /**
     * 票量
     */
    private int count;

    public SaleWindow(int count) {
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    /**
     * 售卖方法
     * 临界区域
     *
     * @param num 买票数
     * @return 买票数，若超卖返回0
     */
    public synchronized int sale(int num) {
        if (this.count >= num) {
            this.count -= num;
            return num;
        }
        return 0;
    }

}
